<template>
	<div class="purchase-manager-info">
		<div class="main_content">
			<div class="main_content_title">
				<div class="left">
					<span>{{ propUpType === 'add' ? $t('publicBtn.add') : propUpType === 'edit' ? $t('publicBtn.edit') :
						$t('publicBtn.detail') }}</span>
					<template v-for="(item, index) in $route.meta.title">
						<span v-if="languageId === item.langId">{{ item.name }}</span>
					</template>
				</div>
				<div class="right" />
			</div>
			<div class="main_content_con">
				<el-form ref="info" :model="info" :rules="rules" label-width="100px" class="demo-ruleForm">
					<div class="content_info">
						<template v-if="propUpType !== 'detail'">
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.supplier')" prop="supplierId">
										<el-select v-model="info.supplierId" filterable :placeholder="$t('placeholderTip.pSelect')"
											style="width:100%">
											<el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.purchaseType')" prop="purchaseType">
										<el-select v-model="info.purchaseType" filterable :placeholder="$t('placeholderTip.pSelect')"
											style="width:100%">
											<el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
										</el-select>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.purchaseSpecies')">
										<el-input readonly :value="info.classifyNum" :placeholder="$t('placeholderTip.bringOut')" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.purchasetotalAmt')">
										<el-input readonly :value="info.totalAmt" :placeholder="$t('placeholderTip.bringOut')" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.purchaseTotality')">
										<el-input readonly :value="info.totalNum" :placeholder="$t('placeholderTip.bringOut')" />
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('publicFormLabel.remark')">
										<el-input v-model="info.remark" type="texdataea" :placeholder="$t('placeholderTip.enter')" />
									</el-form-item>
								</el-col>
							</el-row>
							<div class="line"></div>
							<div class="contentInfo">
								<div class="header">
									<div class="title">{{ $t('text.purchasedProductDetails') }}</div>
									<div class="btn">
										<el-button type="primary" size="mini" @click="addData">{{
											$t('publicBtn.add') }}</el-button>
									</div>
								</div>
								<el-table :data="info.inventories" border style="width: 100%">
									<el-table-column prop="code" :label="$t('formLabel.partNumber')" align="center" />
									<el-table-column prop="name" :label="$t('formLabel.partName')" align="center" />
									<el-table-column prop="alias" :label="$t('formLabel.partAnotherName')" align="center" />
									<el-table-column prop="brand" :label="$t('publicFormLabel.brandName')" align="center" />
									<el-table-column prop="specs" :label="$t('formLabel.specification')" align="center" />
									<el-table-column prop="unit" :label="$t('formLabel.unit')" align="center" />
									<el-table-column :label="$t('formLabel.purchasePrice')" align="center" width="200px">
										<template slot-scope="scope">
											<el-form-item label=" " label-width="2px" :prop="'inventories.' + scope.$index + '.cost'"
												:rules="rules.cost">
												<el-input type="number" v-model="scope.row.cost" :placeholder="$t('placeholderTip.enter')"
													style="width:93%"></el-input>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column prop="stock" :label="$t('formLabel.currentStock')" align="center" />
									<el-table-column :label="$t('formLabel.purchaseQuantity')" align="center" width="200px">
										<template slot-scope="scope">
											<el-form-item label=" " label-width="2px" :prop="'inventories.' + scope.$index + '.num'"
												:rules="rules.num">
												<el-input type="number" v-model="scope.row.num" :placeholder="$t('placeholderTip.enter')"
													style="width:93%"></el-input>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column prop="amount" :label="$t('formLabel.purchaseAmount')" align="center" />
									<el-table-column fixed="right" :label="$t('publicFormLabel.operate')" align="center" width="80px">
										<template slot-scope="scope">
											<el-button @click="deleteRow(scope.$index)" type="text" size="small">{{
												$t('publicBtn.delete') }}</el-button>
										</template>
									</el-table-column>
								</el-table>
							</div>
						</template>
						<template v-else>
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.purchaseOrderNumber')">
										<el-input readonly :value="info.purchaseCode" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.supplier')" prop="supplierId">
										<el-input readonly :value="info.supplierName" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.purchaseType')" prop="purchaseType">
										<el-input readonly :value="info.purchaseTypeName" />
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.purchaseSpecies')">
										<el-input readonly :value="info.classifyNum" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.purchasetotalAmt')">
										<el-input readonly :value="info.totalAmt" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.purchaseTotality')">
										<el-input readonly :value="info.totalNum" />
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('publicFormLabel.remark')">
										<el-input readonly v-model="info.remark" type="texdataea" />
									</el-form-item>
								</el-col>
							</el-row>
							<div class="line"></div>
							<div class="contentInfo">
								<div class="header">
									<div class="title">{{ $t('text.purchasedProductDetails') }}</div>
								</div>
								<el-table :data="info.inventories" border style="width: 100%">
									<el-table-column fixed prop="code" :label="$t('formLabel.partNumber')" align="center" />
									<el-table-column prop="name" :label="$t('formLabel.partName')" align="center" />
									<el-table-column prop="alias" :label="$t('formLabel.partAnotherName')" align="center" />
									<el-table-column prop="brand" :label="$t('publicFormLabel.brandName')" align="center" />
									<el-table-column prop="specs" :label="$t('formLabel.specification')" align="center" />
									<el-table-column prop="unit" :label="$t('formLabel.unit')" align="center" />
									<el-table-column :label="$t('formLabel.purchasePrice')" align="center" width="200px">
										<template slot-scope="scope">
											{{ scope.row.cost }}
										</template>
									</el-table-column>
									<el-table-column prop="stock" :label="$t('formLabel.currentStock')" align="center" />
									<el-table-column prop="num" :label="$t('formLabel.purchaseQuantity')" align="center">
										<template slot-scope="scope">
											{{ scope.row.num }}
										</template>
									</el-table-column>
									<el-table-column prop="amount" :label="$t('formLabel.purchaseAmount')" align="center" />
								</el-table>
							</div>
						</template>
					</div>
				</el-form>
				<div class="footerBtn">
					<el-button @click="getCancle">{{ propUpType !== 'detail' ? $t('el.popconfirm.cancelButtonText') :
						$t('el.popconfirm.close') }}</el-button>
					<el-button v-if="propUpType !== 'detail'" type="primary" @click="addSubmitForm"
						v-loading.fullscreen.lock="fullscreenLoading">{{ $t('el.popconfirm.confirmButtonText') }}</el-button>
				</div>
			</div>
		</div>
		<!-- 添加配件 -->
		<attachmentModel ref="attachmentModel"></attachmentModel>
	</div>
</template>
<script>
import {
	getPurchaseInfo,
	setPurchaselSave,
	getAssSupplierSelectList
} from '@/api/parts-manager'
import { getPresaleAttributeList } from '@/api/public'
import defaultSettings from '@/settings'
import attachmentModel from '@/components/attachment-model'
export default {
	name: '',
	components: {
		attachmentModel
	},
	data() {
		return {
			BASE_IMG: defaultSettings.BASE_IMG,
			info: {
				purchaseCode: '',//采购单号
				supplierId: '',//供应商
				purchaseType: '',//采购类型
				classifyNum: '',//采购种类
				totalNum: '',//采购总数
				totalAmt: '',//采购总金额
				remark: '',//备注
				inventories: [],//明细
			},
			supplierList: [],//供应商
			typeList: [],//采购类型
			rules: {
				supplierId: [
					{
						required: true,
						message: this.$t('placeholderTip.pSelect'),
						trigger: 'change'
					}
				],
				purchaseType: [
					{
						required: true,
						message: this.$t('placeholderTip.pSelect'),
						trigger: 'change'
					}
				],
				cost: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					}
				],
				num: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					}
				],

			},
			propUpType: '', // 'add' edit detail
			fullscreenLoading: false,
		}
	},
	computed: {
		languageId() {
			// 固定语种ID  1:中文  2:英文 3:俄文 4:乌语
			return this.$store.getters.languageId
		},
	},
	watch: {
		'info.inventories': {
			handler: function (val) {
				if (val.length > 0) {
					if (this.propUpType === 'add') {
						var sumNumber = 0
						var number = []
						var amountNumber = 0
						var totalAmt = []
						// 采购数量处理
						this.info.inventories.map(i => {
							if (i.num && i.cost) {
								i.amount = Number(i.num) * Number(i.cost)
								totalAmt.push(Number(i.amount))
							}
							if (i.num) {
								number.push(Number(i.num))
							}
						})
						number.forEach(item => {
							sumNumber = sumNumber + item
						})
						totalAmt.forEach(item => {
							amountNumber = amountNumber + item
						})
						this.info.classifyNum = val.length//采购种类
						this.info.totalNum = sumNumber //采购数量
						this.info.totalAmt = amountNumber //采购总金额
					}
				}
			},
			deep: true
		}
	},
	mounted() {
		window._vm = this
		this.propUpType = this.$route.query.propUpType
		if (this.$route.query.propUpType === 'add') {
			this.getTypeList()
			this.getSupplierist()
		} else if (this.$route.query.id) {
			this.getInfo(this.$route.query.id)
		}
	},
	created() {
		console.log('created')
	},
	activated() { },

	destroyed() { },
	methods: {
		// 供应商
		getSupplierist() {
			getAssSupplierSelectList().then(res => {
				if (res.code === 200) {
					this.supplierList = res.data || []
				}
			})
		},
		// 类型
		getTypeList() {
			// 公共接口
			getPresaleAttributeList(19).then(res => {
				if (res.code === 200) {
					this.typeList = res.data.purchaseTypeList || []
				}
			})
		},
		// 添加明细按钮
		addData() {
			this.$refs.attachmentModel.getOpen()
		},
		// 处理配件列表选中的数据
		getCheckoutData(tar) {
			var data = JSON.parse(tar)
			var obj = {
				materialId: data.id,
				code: data.code,
				name: data.name,
				alias: data.alias,
				brand: data.brandNames,
				specs: data.specs,
				unit: data.smallName,
				stock: data.stock || 0,//的那个库存
				cost: '',//采购单价
				num: '',//采购数量
				amount: '',//采购总价
			}
			const checkId = (items, idToCheck) => {
				return items.filter(item => item.materialId === idToCheck).length > 0;
			}
			// 不重复 push数据
			if (!checkId(this.info.inventories, data.id)) {
				this.info.inventories.push(obj)
			}
		},
		// 删除明细
		deleteRow(index) {
			this.info.inventories.splice(index, 1)
			this.$forceUpdate() // 强制跟新
		},
		// 提交
		addSubmitForm() {
			this.$refs['info'].validate(valid => {
				if (valid) {
					var obj = JSON.parse(JSON.stringify(this.info))
					if (obj.inventories.length === 0) {
						this.$message({
							showClose: true,
							message: this.$t('text.intoInventoriestipInfo'),
							type: 'warning'
						})
						return false
					}
					var params = obj
					this.fullscreenLoading = true
					if (this.propUpType === 'add') {
						setPurchaselSave(params)
							.then(res => {
								if (res.code === 200) {
									this.$message({
										showClose: true,
										message: this.$t('text.addSucceedTip'),
										type: 'success'
									})
									this.fullscreenLoading = false
									this.getCancle()
								}
							})
							.catch(err => {
								this.fullscreenLoading = false
								console.log(err, 'err')
							})
					}
				} else {
					return false
				}
			})
		},
		// 详情
		getInfo(id) {
			const loading = this.$loading({
				lock: true,
				text: this.$t('text.loading'),
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			})
			getPurchaseInfo(id).then(res => {
				if (res.code === 200) {
					this.info = res.data
					loading.close()
				}
			}).catch(() => {
				loading.close()
			})
		},
		// 取消
		getCancle() {
			this.$store.state.tagsView.visitedViews.splice(
				this.$store.state.tagsView.visitedViews.findIndex(
					item => item.path === this.$route.path
				),
				1
			)
			this.$router.go(-1)
		}
	}
}
</script>
<style lang="scss" scoped>
.purchase-manager-info {
	height: 100%;
	width: 100%;
	padding: 20px;
	box-sizing: border-box;
	overflow: hidden;

	&>.main_content {
		width: 99.9%;
		height: 100%;

		&>.main_content_title {
			margin-bottom: 10px;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
		}

		.main_content_con {
			height: calc(100% - 40px);
			width: 100%;
			display: inline-block;
			border: 1px solid #dfe6ec;
			padding: 20px;


			&>.el-form {
				width: 100%;
				height: calc(100% - 40px);

				&>.content_info {
					width: 100%;
					height: 100%;
					overflow: hidden;
					overflow-y: auto;

					.line {
						height: 1px;
						border: 1px solid #ebeef5;
					}

					.el-table {
						::v-deep th {
							line-height: 40px;
							padding: unset;
							background-color: #f2f2f2;
						}
					}
				}


			}

			.footerBtn {
				width: 100%;
				display: flex;
				justify-content: center;
			}

			.cardBox {
				width: 104px;
				height: auto;
				float: left;
				position: relative;

				&>.name {
					text-align: center;
					color: #999;
					font-size: 12px;
				}
			}

			.el-button:hover,
			.el-button:focus {
				color: #000;
			}

			.contentInfo {
				margin-top: 22px;

				&>.header {
					margin-bottom: 22px;
					display: flex;
					justify-content: space-between;
					color: #606266;

					&>.title {
						font-size: 14px;
						font-weight: bold;
					}

				}
			}
		}
	}
}
</style>

